package com.ekuaitu.kuaitu.ble;

import com.inuker.bluetooth.library.connect.response.BleReadResponse;
import com.inuker.bluetooth.library.connect.response.BleWriteResponse;

import java.util.UUID;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import static com.inuker.bluetooth.library.Constants.REQUEST_SUCCESS;

/**
 * Created by jieyaozu on 2017/5/4.
 */

public class BlueUtils {
    public static final UUID serverUUID = UUID.fromString("0000fee7-0000-1000-8000-00805f9b34fb");
    public static final UUID readDataUUID = UUID.fromString("000036f6-0000-1000-8000-00805f9b34fb");
    public static final UUID writeDataUUID = UUID.fromString("000036f5-0000-1000-8000-00805f9b34fb");

    // 加密
    public static byte[] Encrypt(byte[] sSrc, byte[] sKey) {
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(sKey, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
            //"算法/模式/补码方式"
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(sSrc);
            return encrypted;
            //此处使用BASE64做转码功能，同时能起到2次加密的作用。
        } catch (Exception ex) {
            return null;
        }
    }

    // 解密
    public static byte[] decrypt(byte[] sSrc, byte[] sKey) {
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(sKey, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] dncrypted = cipher.doFinal(sSrc);
            return dncrypted;
        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * 向锁发送指令
     *
     * @param data    发送的指令
     * @param loadKey 从服务器上获得的key
     * @param mac     藍牙锁的mac地址
     */
    public static void sendData(byte[] data, final byte[] loadKey, final String mac) {
        byte[] miwen = BlueUtils.Encrypt(data, loadKey);
        //发送命令
        ClientManager.getClient().write(mac, serverUUID, writeDataUUID, miwen, new BleWriteResponse() {
            @Override
            public void onResponse(int code) {
                if (code == REQUEST_SUCCESS) {
                    //读取结果
                    ClientManager.getClient().read(mac, serverUUID, readDataUUID, new BleReadResponse() {
                        @Override
                        public void onResponse(int code, byte[] data) {

                        }
                    });
                }
            }
        });
    }
}
